package admin

import (
	"strconv"
	"strings"
	"tcsc/models"
	"tcsc/sword"

	"github.com/astaxie/beego"
)

type Page struct {
	BaseController
}

func (c *Page) Get() {
	gid := c.Gid
	c.Data["column"] = models.Query(`select id,name from mt_column where type='d' and status=1 and pid=0 and gid=?`, gid)
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	w = append(w, `a.status=1`)
	w = append(w, `a.gid=`+gid)
	cid := c.GetString("cid")
	c.Data["cid"] = cid
	if cid != "" {
		w = append(w, `a.cid=`+cid)
	}
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num
	ob := ` order by a.sort desc,a.addtime desc`
	sql := `select a.*,c.pathname,b.name as cname from mt_page a left join mt_column b on a.cid=b.id left join mt_resources c 
	on a.img=c.id where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_page a where ` + ws
	info := models.Query(sql)
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/page/index?cid=` + cid + `&`
	c.TplName = "admin/page/index.html"
}

type PageAE struct {
	BaseController
}

func (c *PageAE) Get() {
	gid := c.Gid
	c.Data["column"] = models.Query(`select id,name from mt_column where type='d' and status=1 and pid=0 and gid=?`, gid)
	id := c.GetString("id")
	if id != "" {
		if info := models.Query(`select a.*,b.pathname from mt_page a left join mt_resources b on a.img=b.id where a.id=` + id); info != nil {
			c.Data["info"] = info[0]
		} else {
			c.Ctx.Redirect(302, "/admin/page/index")
		}
	}
	c.TplName = "admin/page/ae.html"
}
func (c *PageAE) Post() {
	defer c.ServeJSON()
	input := c.Input()
	gid := c.Gid
	input.Set("gid", gid)
	input.Set("content", sword.CkeditorChange(c.GetString("content")))
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
	}
	if res, err := models.Save("mt_page", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		var r models.Mt_systems_record
		r.Tid = int(res)
		if input.Get("id") == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 23
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
}

type PageContent struct {
	BaseController
}

func (c *PageContent) Get() {
	id := c.GetString("id")
	if id != "" {
		if info := models.Query(`select a.*,b.pathname,c.name as cname from mt_news a left join mt_resources b on a.img=b.id left join mt_column c 
		on a.cid=c.id where a.id=` + id); info != nil {
			c.Data["info"] = info[0]
		} else {
			c.Ctx.Redirect(302, "/admin/page/index")
		}
	} else {
		c.Ctx.Redirect(302, "/admin/page/index")
	}
	c.TplName = "admin/news/content.html"
}
